import React, { Fragment } from "react";
import { Chart, Geom, Axis, Tooltip, Legend } from "bizcharts";
import DataSet from "@antv/data-set";
import numeral from "numeral";
import moment from "moment";
import autoHeight from "../../../../../components/Charts/autoHeight";

@autoHeight()
export default class StackedBar extends React.Component {
  componentWillUnmount() {
    this.chart = null;
  }

  getG2Instance = chart => {
    this.chart = chart;
  };

  render() {
    // if (this.chart) { // todo 没用的好像
    //   this.chart.forceFit();
    // }
    const {
      title,
      height = 400,
      padding = [60, 10, 40, 80],
      titleMap = {
        y1: "y1",
        y2: "y2"
      },
      failCount,
      successCount,
      rate,
      data = [  
        {
          x: '2020-01-01',
          y1: 0,
          y2: 0
        }
      ]
    } = this.props;
    const ds = new DataSet();
    const dv = ds.createView().source(data);
    
    dv.transform({
      type: "map",
      callback(row) {
        const newRow = { ...row };
        newRow[titleMap.y1] = row.y1;
        newRow[titleMap.y2] = row.y2;
        return newRow;
      }
    }).transform({
      type: "fold",
      fields: [titleMap.y1, titleMap.y2],
      // 展开字段集
      key: "key",
      // key字段
      value: "value" // value字段
    });

    let scale = {};
    if (data.length&&data.length<=12) {
      scale = {
        x: {
          type: "cat",
          range: [0.04, 0.96],
          formatter: val => moment(val).format("YYYYMM")
        },
        value: {
          min: 0
        }
      };
    }else if (data.length>12) {
      scale = {
        x: {
          type: "cat",
          range: [0.04, 0.96],
          formatter: val => moment(val).format("MM.DD")
        },
        value: {
          min: 0
        }
      };
    } 
    else {
      scale = {
        x: {
          type: "linear",
          tickInterval: 1,
          tickCount: 14,
          min: 0,
          formatter: val =>
            moment()
              .add(val - 15, "days")
              .format("MM.DD")
        },
        value: {
          min: 0,
          tickInterval: 15
        }
      };
    }
    return (
      <Fragment>
        {title && title}
        <Chart
          height={height}
          data={dv}
          padding={padding}
          forceFit
          scale={scale}
          onGetG2Instance={this.getG2Instance}
        >
          <Legend
          /* marker="circle" */
            position="center-left"
            useHtml={true}
            size={2}
            itemTpl={(value, color, checked, index) => {
              // let total = 0;
              // const arr = dv.origin;
              // console.log({value, color, checked, index});
              // for (let i = 0; i < arr.length; i += 1) {
              //   total += arr[i][`y${index + 1}`];
              // }
              const total = value === '成功量' ? successCount : failCount;
              const isChecked = checked ? "checked" : "unChecked";
              return `<li class="g2-legend-list-item item-${index} ${isChecked}" data-color="${color}" data-value="${value}" style="cursor: pointer;font-size: 14px; ">
                ${value === '成功量' ? `<span style="color:rgba(0,0,0); margin-left:50px">成功率 :</span><span style="color:rgba(0,0,0); margin-left:4px; font-weight:600;">${rate}</span>` : ''}
                <i  class="g2-legend-marker" style="margin-left:30px;margin-right:10px;background-color: ${color};"></i>
                <span class="g2-legend-text" style="color:rgba(0,0,0);">${value} :</span>
                <span style="font-size:14px; color:black; " >${numeral(
                  total
              ).format("0,0")}</span>
              
              </li>`;
            }}
            g2-legend={{ whiteSpace: "nowrap", left: 20 }}
            g2-legend-marker={{ width: "20px", height: "2px", borderRadius: 0}}
          />
          <Axis name="x" />
          <Axis name="value" />
          <Tooltip
            g2-tooltip={{
              backgroundColor: "rgba(0,0,0,.75)",
              color: "#fff",
              boxShadow: "0px 2px 8px 0px rgba(0,0,0,0.15)"
            }}
            g2-tooltip-value={{
              float: "none",
              marginLeft: "0px"
            }}
            // showTitle={false}
          />
          <Geom 
            type="lineStack" 
            position="x*value" 
            size={2} 
            shape={"smooth"} 
            color={["key", ['rgba(0, 150, 255, 1)', 'rgba(255,110,97, 1)']]}
            tooltip={[
              "value*key*x",
              (value, key, x) => ({
                title: x,
                name: `${key}：`,
                value: numeral(value).format("0,0")
              })
            ]} 
          />
          <Geom
            type="areaStack"
            position="x*value"
            shape={"smooth"}
            color={["key", ['l (90) 0:rgba(0, 150, 255, 0.5) 1:rgba(0, 150, 255, 0.1)', 'l (90) 0:rgba(255,100,97, 0.5) 1:rgba(255,100,97, 0.1)']]}
            /* style={{
              stroke: "#fff",
              lineWidth: 1
            }} */
            size={2}
          />
        </Chart>
      </Fragment>
    );
  }
}
